package com.bruce.spring.http.service;

import org.apache.coyote.UpgradeProtocol;
import org.apache.coyote.http2.Http2Protocol;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

@Component
public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        factory.addConnectorCustomizers(connector -> {
            UpgradeProtocol[] upgradeProtocols = connector.findUpgradeProtocols();
            if (upgradeProtocols == null) {
                return;
            }
            for (UpgradeProtocol upgradeProtocol : upgradeProtocols) {
                if (upgradeProtocol instanceof Http2Protocol http2Protocol) {
                    customHttp2Protocol(http2Protocol);
                }
            }
        });
    }


    private void customHttp2Protocol(Http2Protocol http2Protocol) {
        http2Protocol.setKeepAliveTimeout(http2Protocol.getKeepAliveTimeout() + 10000);
    }


}